import { defineConfig } from 'vite'
import Vue from '@vitejs/plugin-vue'
import VueMacros from 'vue-macros/vite'
import Inspect from 'vite-plugin-inspect'
import vueJsx from '@vitejs/plugin-vue-jsx'

export default defineConfig({
  plugins: [
    VueMacros({
      plugins: {
        vue: Vue(),
        vueJsx: vueJsx(),
      },
    }),
    Inspect(),
  ],
  server: {
    //开启局域网
    cors: true,
    host: '0.0.0.0',
    proxy: {
      // 代理SSE请求
      '/api/sse': {
        target: 'https://wss.lke.cloud.tencent.com',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api\/sse/, '/v1/qbot/chat/sse'),
        configure: (proxy, _options) => {
          proxy.on('error', (err, _req, _res) => {
            console.log('proxy error', err);
          });
          proxy.on('proxyReq', (proxyReq, req, _res) => {
            console.log('Sending Request:', req.method, req.url);
            
            // 确保内容类型正确
            if (!proxyReq.getHeader('Content-Type')) {
              proxyReq.setHeader('Content-Type', 'application/json');
            }
            
            // 添加必要的SSE头
            if (req.method === 'POST') {
              proxyReq.setHeader('Accept', 'text/event-stream');
              proxyReq.setHeader('Cache-Control', 'no-cache');
              proxyReq.setHeader('Connection', 'keep-alive');
            }
          });
          proxy.on('proxyRes', (proxyRes, req, _res) => {
            console.log('Received Response from:', req.url, proxyRes.statusCode, proxyRes.statusMessage);
            
            // 记录响应头以便调试
            console.log('Response Headers:', JSON.stringify(proxyRes.headers, null, 2));
          });
        },
      },
      'https://lke.tencentcloudapi.com': {
        target: 'https://lke.tencentcloudapi.com',
        changeOrigin: true,
        // rewrite: (path) => path.replace(/^\/tencent\/v1/, ''),
        configure: (proxy, _options) => {
          proxy.on('error', (err, _req, _res) => {
            console.log('proxy error', err);
          });
          proxy.on('proxyRes', (proxyRes, req, _res) => {
            proxyRes.headers['Access-Control-Allow-Origin'] = '*';
          });
          proxy.on('proxyReq', (proxyReq, req, _res) => {
            // 设置referer
            proxyReq.setHeader('Referer', 'https://lke.tencentcloudapi.com');
          });
        }
      }
    }
  },
  resolve: {
    alias: {
      '@': '/src',
      '~': './',
    },
    extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue'],
  },
})
